/**
 * Created by tianling on 2016/12/25.
 */

module.exports = class {
    constructor() {
        this.key = "cms:article:label";
    }

    static init() {
        return new this();
    }

    /**
     * 获取系统模块列表
     * @param isReFlash
     * @param CB
     */
    async getItemsByDB() {
        return await global.DataBase.cms_article_label.Access.findAll({
            where: {
                al_del_flag: 0
            },
            order: ['al_sort'],
            raw: true
        });
    };

    async Sync() {
        let ret = {};
        let items = await this.getItemsByDB();
        let partners = await global.DataBase.base.query("select distinct al_partners_id from cms_article_label left join iframe_orgstruct on OS_ID=al_partners_id where OS_IsDel=0 and OS_Type=:OS_Type", {
            OS_Type: '001'
        });
        for (let partner of partners) {
            ret[partner.al_partners_id] = await global.DataBase.cms_article_label.Access.findAll({
                where: {
                    al_partners_id: partner.al_partners_id
                },
                raw: true
            })
        }
        ret['all'] = items;
        if (!global.Config.isShareMemory) {
            global.articleLabels = ret;
        } else {
            let redis = global.Redis.getClient();
            let pipeline = redis.pipeline();
            for (let key in ret) {
                if (key) {
                    pipeline.set(this.key + ":" + key, JSON.stringify(ret[key]));
                }
            }
            await pipeline.exec();
        }
        log.info("加载CMS文章分类成功");
        return true;
    };

    /**
     * 获取指定Label的字典表
     * @param Label
     * @constructor
     */
    async getArticleLabelItems(partnersId) {
        let Items = [];
        if (partnersId == undefined || partnersId == null || partnersId === 0 || partnersId === "0") {
            if (!global.Config.isShareMemory) {
                Items = global.articleLabels["all"];
            } else {
                let redis = global.Redis.getClient();
                Items = await redis.get(this.key + ":all");
            }

        } else {
            if (partnersId != '') {
                if (!global.Config.isShareMemory) {
                    Items = global.articleLabels[partnersId];
                } else {
                    let redis = global.Redis.getClient();
                    Items = await redis.get(this.key + ":" + partnersId);
                }
            }
        }
        return Items;
    };

    /**
     * 根据code获取item
     * @param partnersId 企业id
     * @param code String 分类编码
     * @returns {*}
     * @constructor
     */
    async getItemByCode(partnersId, code) {
        let Items = await this.getArticleLabelItems(partnersId);
        let _items = Items.filter(function (item) {
            if (item.al_code === code) {
                return true;
            }
        });
        if (_items.length > 0) {
            return _items[0];
        }
        return null;
    };

    /**
     * 根据ID查询
     * @param partnersId 企业ID
     * @param ID 分类ID
     * @returns {Promise<*>}
     * @constructor
     */
    async getItemByID(partnersId, ID) {
        let Items = await this.getArticleLabelItems(partnersId);
        let _items = Items.filter(function (item) {
            if (item.al_id === Number(ID)) {
                return true;
            }
        });
        if (_items.length > 0) {
            return _items[0];
        }
        return null;
    };



    async getChildrenValues(partnersId, ID) {
        let cur = await this.getItemByID(partnersId, ID);
        let Items = await this.getArticleLabelItems(partnersId);
        let Childrens = [];
        for (let i = 0; i < Items.length; i++) {
            let item = Items[i];
            if (item.al_parent_id === cur.al_id) {
                Childrens.push("" + item.al_id + "");
                if (item.al_isparent) {
                    Childrens = Childrens.concat(await this.getChildrenValuesByID(partnersId, item.al_id));
                }
            }
        }
        return Childrens;
    };

    async getChildrensModel(partnersId, ID) {
        let cur = await this.getItemByID(partnersId, ID);
        let Items = await this.getArticleLabelItems(partnersId);
        let Childrens = [];
        for (let i = 0; i < Items.length; i++) {
            let item = Items[i];
            if (item.al_parent_id === cur.al_id) {
                Childrens.push(item);
                if (item.al_isparent) {
                    Childrens = Childrens.concat(await this.getChildrenValuesByID(partnersId, item.al_id));
                }
            }
        }
        return Childrens;
    };

    /**
     * 获取所有父级的值数组
     * @param {*} Label
     * @param {*} value
     */
    async GetParentsValue(partnersId, value) {
        var ParentsModels = await this.getParentsModel(partnersId, value);
        var Values = [];
        for (var i = ParentsModels.length - 1; i > -1; i--) {
            Values.push(ParentsModels[i].zd_value);
        }
        return Values;
    };

    /**
     * 获取所有父级的名称数组
     * @param {*} Label
     * @param {*} value
     */
    async GetParentsName(partnersId, Label, value) {
        let ParentsModels = await this.getParentsModel(partnersId, value);
        let Names = [];
        for (let i = ParentsModels.length - 1; i > -1; i--) {
            Names.push(ParentsModels[i].al_name);
        }
        return Names;
    };

    /**获取所有的父级模型**/
    async getParentsModel(partnersId, ID) {
        let item = await this.getItemByID(partnersId, ID);
        if (item) {
            return await this.getParentsModelByID(partnersId, item.al_id);
        }
        return [];
    };

    async getParentsModelByID(partnersId, ChildrenID) {
        let Parents = [];
        let item = await this.getItemByID(partnersId, ChildrenID);
        if (item) {
            Parents.push(item);
            Parents = await Parents.concat(this.getParentsModelByID(partnersId, item.al_parent_id));
        }
        return Parents;
    };

    async getParentsValueByID(partnersId, ChildrenID) {
        let Parents = [];
        let item = await this.getItemByID(partnersId, ChildrenID);
        if (item) {
            Parents.push(item.al_id);
            Parents = await Parents.concat(this.getParentsModelByID(partnersId, item.al_parent_id));
        }
        return Parents;
    };

    async getTreeData(partnersId, ParentID, Items) {
        if (!Items) {
            Items = await this.getArticleLabelItems(partnersId);
        }
        let data = [];
        let getChildrens = function (pid) {
            let cdata = [];
            for (let i = 0; i < Items.length; i++) {
                let item = Items[i];
                if (item.al_parent_id === pid) {
                    let data_item = {
                        title: item.al_name,
                        value: item.al_id,
                        key: item.al_id,
                        children: getChildrens(item.al_id)
                    };
                    if (data_item.children.length === 0) delete data_item.children;
                    cdata.push(data_item);
                }
            }
            return cdata;
        };
        if (ParentID > 0) {
            let curP = await this.getItemByID(partnersId, ParentID);
            data.push({
                title: item.al_name,
                value: item.al_id,
                key: item.al_id,
                children: getChildrens(curP.al_id)
            });
        } else {
            data = getChildrens(0);
        }
        return data;

    };


};